package cn.com.dcsgo.controller;

import cn.com.dcsgo.pojo.Schedule;
import cn.com.dcsgo.service.ScheduleService;
import cn.com.dcsgo.utils.PageResult;
import cn.com.dcsgo.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * ScheduleController
 *
 * @author Dcsgo
 * @since 2025/3/8 16:23
 */
@Slf4j
@CrossOrigin//允许跨域访问 (Access-Control-Allow-Origin) 可添加到方法或类上
@RestController
@RequestMapping("study-plans")
public class ScheduleController {
    private final ScheduleService scheduleService;

    public ScheduleController(ScheduleService scheduleService) {
        this.scheduleService = scheduleService;
    }

    @GetMapping("/{pageNum}/{pageSize}")
    public R<PageResult<Schedule>> findAllByPage(@PathVariable int pageNum, @PathVariable int pageSize) {
        return R.success(scheduleService.findAllByPage(pageNum, pageSize));
    }

    @DeleteMapping("{id}")
    public R<?> remove(@PathVariable int id) {
        if (scheduleService.deleteById(id) != 0) {
            return R.success();
        }
        return R.fail();
    }

    @PostMapping
    public R<?> addOne(@RequestBody @Validated Schedule schedule,
                             BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            // 获取错误信息
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            StringBuilder errorMessages = new StringBuilder();
            for (FieldError fieldError : fieldErrors) {
                errorMessages.append("Field: ").append(fieldError.getField())
                        .append(", Error: ").append(fieldError.getDefaultMessage())
                        .append("; ");
            }
            log.info("addOne.bindingResult.hasErrors() error:{}", errorMessages);
            return R.fail(errorMessages);
        }
        if (scheduleService.addOne(schedule) != 0) {
            return R.success(schedule.getId());
        }
        return R.fail();
    }

    @PutMapping
    public R<?> update(@RequestBody Schedule schedule) {
        if (schedule.getId() == null) {
            return R.fail();
        }
        if (scheduleService.updateById(schedule) != 0) {
            return R.success();
        }
        return R.fail();
    }
}
